#pragma once
#include <iostream>
#include <string>
#include <set>
class CommendExec
{
public:

	CommendExec()
	{
		_white_list.insert("ls");
        _white_list.insert("pwd");
        _white_list.insert("ls -l");
        _white_list.insert("ll");
        _white_list.insert("touch");
        _white_list.insert("who");
        _white_list.insert("whoami");
	}
	bool SafeCheck(std::string &command)
	{
		// 白名单检查, 只有白名单中的命令才允许执行, 否则拒绝执行, 并返回false
		return _white_list.find(command) != _white_list.end();
	}
 // 给你一个命令字符串"ls -l", 让你执行，执行完，把结果返回
	std::string Execute(std::string command)
	{
		if(!SafeCheck(command))
		{
			return std::string("Command not allowed");
		}
		FILE* fp = popen(command.c_str(), "r");
		if(fp == nullptr)
		{
			return std::string("Failed to execute command");
		}
		char fbuffer[1024];
		std::string result = "";
		while(true)
		{
			char *ret = fgets(fbuffer,sizeof(fbuffer),fp);
			if(ret == nullptr)
			{
				break;
			}
			result += ret;
		}
		pclose(fp);

		return result.empty() ? std::string("Command executed successfully, but no output") : result;
	}
private:
	std::set<std::string> _white_list;
};